<template>
  <div class="team-settings-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button
          :icon="ArrowLeft"
          @click="goBack"
          link
          class="back-button"
        >
          返回{{ t('team.teamDetail') }}
        </el-button>
        <div class="page-title">
          <h2>{{ t('team.teamSettings') }}</h2>
          <p class="page-subtitle">管理团队的高级设置和权限配置</p>
        </div>
      </div>
      <div class="header-right">
        <el-tag v-if="teamInfo" :type="getStatusTagType(teamInfo.status)">
          {{ getStatusText(teamInfo.status) }}
        </el-tag>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="pageLoading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 权限不足提示 -->
    <div v-else-if="!canManageSettings" class="no-permission">
      <el-result
        icon="warning"
        title="权限不足"
        sub-title="只有团队所有者和管理员可以访问团队设置"
      >
        <template #extra>
          <el-button @click="goBack">返回团队详情</el-button>
        </template>
      </el-result>
    </div>

    <!-- 设置内容 -->
    <div v-else class="settings-content">
      <!-- 团队基本信息卡片 -->
      <el-card class="team-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>团队信息</span>
          </div>
        </template>
        <div v-if="teamInfo" class="team-basic-info">
          <div class="info-item">
            <span class="label">团队名称：</span>
            <span class="value">{{ teamInfo.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">团队描述：</span>
            <span class="value">{{ teamInfo.description || '暂无描述' }}</span>
          </div>
          <div class="info-item">
            <span class="label">成员数量：</span>
            <span class="value">{{ teamInfo.currentMembers }} / {{ teamInfo.maxMembers }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(teamInfo.createdAt) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 高级设置组件 -->
      <TeamAdvancedSettings
        v-if="teamInfo && currentUserRole"
        :team-id="teamInfo.id"
        :current-user-role="currentUserRole"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import TeamAdvancedSettings from '@/components/team/TeamAdvancedSettings.vue'
import teamApiDefault, { teamApi } from '@/api/team'
import type { Team, TeamMember } from '@/types/team'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { t } = useI18n()

// 响应式数据
const pageLoading = ref(true)
const teamInfo = ref<Team | null>(null)
const currentUserRole = ref<string>('')

// 计算属性
const teamId = computed(() => {
  return parseInt(route.params.id as string)
})

const canManageSettings = computed(() => {
  // 只有在数据加载完成且有角色信息时才进行权限检查
  if (pageLoading.value || !currentUserRole.value) {
    return true // 加载中时暂时允许访问，避免闪烁
  }
  return currentUserRole.value === 'OWNER' || currentUserRole.value === 'ADMIN'
})

// 方法
const goBack = () => {
  router.push(`/dashboard/team/${teamId.value}`)
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'ARCHIVED': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'ARCHIVED': '已归档'
  }
  return statusMap[status] || status
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadTeamInfo = async () => {
  try {
    const response = await teamApi.getTeamDetail(teamId.value)
    // RickPan API返回格式：{code: 200, message: '获取成功', data: {...}}
    if (response.code === 200 && response.data) {
      teamInfo.value = response.data
    } else {
      console.error('获取团队信息失败:', response)
      ElMessage.error(response.message || '获取团队信息失败')
    }
  } catch (error: any) {
    console.error('获取团队信息失败:', error)
    ElMessage.error(error.response?.data?.message || '获取团队信息失败')
  }
}

const loadUserRole = async () => {
  try {
    const response = await teamApiDefault.getTeamMembers(teamId.value)

    // RickPan API返回格式：{code: 200, message: '获取成功', data: [...]}
    if (response.code === 200 && response.data) {
      // 尝试多种方式获取用户ID
      const currentUserId = userStore.userInfo?.id || userStore.getCurrentUserId()

      const currentMember = response.data.find((member: TeamMember) => member.userId === currentUserId)

      if (currentMember) {
        currentUserRole.value = currentMember.role
      }
    }
  } catch (error: any) {
    console.error('获取用户角色失败:', error)
  }
}

const initPage = async () => {
  pageLoading.value = true
  try {
    await Promise.all([
      loadTeamInfo(),
      loadUserRole()
    ])
  } finally {
    pageLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  initPage()
})
</script>

<style scoped lang="scss">
.team-settings-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .header-left {
      display: flex;
      align-items: flex-start;
      gap: 16px;

      .back-button {
        margin-top: 4px;
        color: var(--el-color-primary);
        
        &:hover {
          background-color: var(--el-color-primary-light-9);
        }
      }

      .page-title {
        h2 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }

        .page-subtitle {
          margin: 0;
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .header-right {
      margin-top: 8px;
    }
  }

  .loading-container {
    padding: 24px;
  }

  .no-permission {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }

  .settings-content {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .team-info-card {
      .card-header {
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .team-basic-info {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 16px;

        .info-item {
          display: flex;
          align-items: center;

          .label {
            font-weight: 500;
            color: var(--el-text-color-regular);
            min-width: 80px;
          }

          .value {
            color: var(--el-text-color-primary);
            flex: 1;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .team-settings-container {
    padding: 16px;

    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;

      .header-left {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }
    }

    .settings-content {
      .team-info-card {
        .team-basic-info {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>
